package com.ruoyi.system.service.impl;

import java.io.*;
import java.nio.file.Files;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.ruoyi.system.domain.BEFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.BEAffileMapper;
import com.ruoyi.system.domain.BEAffile;
import com.ruoyi.system.service.IBEAffileService;
import com.ruoyi.system.domain.comment.FileComment;

/**
 * 文件管理审核后Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-06-24
 */
@Service
public class BEAffileServiceImpl implements IBEAffileService 
{
    @Autowired
    private BEAffileMapper bEAffileMapper;

    private String path="D:\\ruoyi\\uploadPath";
    private String profile = "/profile";
    /**
     * 查询文件管理审核后
     * 
     * @param id 文件管理审核后主键
     * @return 文件管理审核后
     */
    @Override
    public BEAffile selectBEAffileById(String id)
    {
        return bEAffileMapper.selectBEAffileById(id);
    }



    /**
     * 查询文件注释信息列表
     *
     * @return 文件信息集合
     */
    public List<FileComment> selectBEAffileComList() {
        return bEAffileMapper.selectBEAffileComList();
    }



    /**
     * 查询文件管理审核后列表
     * 
     * @param bEAffile 文件管理审核后
     * @return 文件管理审核后
     */
    @Override
    public List<BEAffile> selectBEAffileList(BEAffile bEAffile)
    {
        return bEAffileMapper.selectBEAffileList(bEAffile);
    }

    /**
     * 新增文件管理审核后
     * 
     * @param bEAffile 文件管理审核后
     * @return 结果
     */
    @Override
    public int insertBEAffile(BEAffile bEAffile)
    {
        return bEAffileMapper.insertBEAffile(bEAffile);
    }

    /**
     * 修改文件管理审核后
     * 
     * @param bEAffile 文件管理审核后
     * @return 结果
     */
    @Override
    public int updateBEAffile(BEAffile bEAffile)
    {
        return bEAffileMapper.updateBEAffile(bEAffile);
    }

    /**
     * 批量删除文件管理审核后
     * 
     * @param ids 需要删除的文件管理审核后主键
     * @return 结果
     */
    @Override
    public int deleteBEAffileByIds(String[] ids)
    {
        return bEAffileMapper.deleteBEAffileByIds(ids);
    }

    /**
     * 删除文件管理审核后信息
     * 
     * @param id 文件管理审核后主键
     * @return 结果
     */
    @Override
    public int deleteBEAffileById(String id)
    {
        return bEAffileMapper.deleteBEAffileById(id);
    }


    public ResponseEntity<byte[]> getpdf(String id){
        try {
            // 从classpath中加载PDF文件

            BEAffile beFile = bEAffileMapper.selectBEAffileById(id);
            String fullPath = beFile.getFilepath();
            String cleanPath = removePrefix(fullPath, profile);
            File localFile = new File(path + File.separator + cleanPath + File.separator);
            // 将PDF文件内容转换为字节数组
            byte[] localBytes = Files.readAllBytes(localFile.toPath());
            return ResponseEntity.ok().header("Content-Type", "application/pdf").body(localBytes);
        }catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }
    public static String removePrefix(String original, String prefix) {
        if (original.startsWith(prefix)) {
            // 去除前缀并确保路径仍然以斜杠开始
            return "/" + original.substring(prefix.length() + 1);
        } else {
            // 如果原始路径不以指定前缀开头，则返回原始路径
            return original;
        }
    }
    public ResponseEntity<byte[]> downloadMore(String[] ids){
        String filePath = "D:\\temporaryFolder";
        String zipPath = "D:\\fileZip.zip";
        try{
            File folder = new File(filePath);
            if(!folder.exists()){
                folder.mkdirs();
            }

            for(String fileId : ids){
                String id = fileId.replace("++","/");
                BEAffile beFile = bEAffileMapper.selectBEAffileById(id);
                String fullPath = beFile.getFilepath();
                String cleanPath = removePrefix(fullPath, profile);
                File oldFile = new File(path + File.separator + cleanPath + File.separator);
                String targetPath = "D:\\temporaryFolder\\" + beFile.getWenJianName() + "." + beFile.getFiletype();
                File newFile = new File(targetPath);
                Files.copy(oldFile.toPath(),newFile.toPath());
            }
            zipFolder(filePath,zipPath);
            byte[] zipFileData = readZipFile(zipPath);

            File folderToDelete = new File(filePath);
            deleteFolderAndContents(folderToDelete);
            File zipFileToDelete = new File(zipPath);
            deleteFile(zipFileToDelete);
            return ResponseEntity.ok().header("Content-Type","application/zip").body(zipFileData);
        }catch (IOException e){
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }
    public void zipFolder(String folderPath, String zipFileName) throws IOException {
        File folder = new File(folderPath);

        if (folder.exists() && folder.isDirectory()) {
            try (FileOutputStream fos = new FileOutputStream(zipFileName);
                 ZipOutputStream zos = new ZipOutputStream(fos)) {
                for (File file : folder.listFiles()) {
                    if (file.isFile()) {
                        ZipEntry zipEntry = new ZipEntry(file.getName());
                        zos.putNextEntry(zipEntry);

                        try (FileInputStream fis = new FileInputStream(file)) {
                            byte[] buffer = new byte[1024];
                            int length;
                            while ((length = fis.read(buffer)) > 0) {
                                zos.write(buffer, 0, length);
                            }
                        }

                        zos.closeEntry();
                    }
                }
            }
        }
    }

    private byte[] readZipFile(String zipFileName) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileInputStream fis = new FileInputStream(zipFileName);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = fis.read(buffer)) != -1) {
            baos.write(buffer, 0, bytesRead);
        }
        fis.close();
        return baos.toByteArray();
    }

    private static boolean deleteFolderAndContents(File folder) {
        if (folder.exists()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        if (!deleteFolderAndContents(file)) {
                            return false;
                        }
                    } else {
                        if (!deleteFile(file)) {
                            return false;
                        }
                    }
                }
            }
            return folder.delete();
        }
        return false;
    }

    private static boolean deleteFile(File file) {
        if (file.exists()) {
            return file.delete();
        }
        return false;
    }

}
